<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2018/2/24
 * Time: 16:13
 */

namespace app\common\model;

use think\Exception;
use think\Log;
use think\Model;

class Withdrawals extends Model 
{
    protected function getStatusAttr($value)
    {
        $status = [0 => '待审核',1 => '已通过',2 => '已拒绝',3 => '已冻结'];
        return ['val' => $value, 'text' => $status[$value]];
    }

    public function cash($payment_id, $money, $user_id)
    {
        $user_model = model('Users');
        $user_info = $user_model->lock(true)->where('user_id', $user_id)->find();
        if ($user_info['user_balance'] < $money)
        {
            return "很抱歉，您的余额不够";
        }
        $user_data = [
            'user_balance' => $user_info['user_balance'] - $money,
        ];
        $cash_data = [
            'payment'   => $payment_id,
            'amount'    => $money,
            'user_id'   => $user_info['user_id'],
            'add_time'  => time(),
            'modified'  => time(),
            'status'    => 0,
        ];
        $transaction_data = [
            'flow'      => 2,
            'amount'    => -$money,
            'balance'   => $user_info['user_balance'] - $money,
            'type'      => 3,
            'user_id'   => $user_info['user_id'],
            'add_time'  => time()
        ];
        $this->startTrans();
        try {
            $this->save($cash_data);
            $withdraw_id = $this->withdraw_id;
            model('Transactions')->save($transaction_data);
            $log_data = [
                'withdraw_id' => $withdraw_id,
                'status'      => 0,
                'add_time'    => time(),
                'remark'      => '申请提现',
            ];
            model('WithdrawLogs')->save($log_data);
            model('Users')->save($user_data,['user_id'=> $user_info['user_id']]);
            $this->commit();
            return true;
        } catch (Exception $e) {
            Log::record($e->getMessage());
            $this->rollback();
            return false;
        }
    }
}
